import { ComponentInfoType } from "./index";

export function getNextSelectedId(fe_id: string, componentList: ComponentInfoType) {
  const visibleComponentList = componentList.filter((c) => !c.isHidden);
  const index = visibleComponentList.findIndex((item) => item.fe_id === fe_id);
  if (index < 0) return "";
  //重新计算selectId
  let newSelectedId = "";
  const length = componentList.length;
  if (length <= 1) {
    newSelectedId = "";
  } else {
    //组件长度>1
    if (index + 1 == length) {
      //要删除最后一个,就要选中上一个
      newSelectedId = componentList[index - 1].fe_id;
    } else {
      //选中下一个
      newSelectedId = componentList[index + 1].fe_id;
    }
  }
  return newSelectedId;
}

//插入新组建
export function insertNewComponent(draft: ComponentStateType, newCompoent: ComponentInfoType) {
  const { selectedId, componentList } = draft;
  const index = componentList.findIndex((item) => item.fe_id === selectedId);
  if (index !== -1) {
    //未选中 插入到index后面
    draft.componentList.splice(index + 1, 0, newCompoent);
  } else {
    //选中的话放在后面
    draft.componentList.push(newCompoent);
  }
  draft.selectedId = newCompoent.fe_id;
}
